#include "ImageModel2.h"
ImageModel2* ImageModel2::instance = nullptr;


ImageModel2::ImageModel2(QObject *parent) : QAbstractListModel(parent) {
    ImageLabelModel data1("111111111");
    ImageLabelModel data2("222222222222");
    _dataList_.append(data1);
    _dataList_.append(data2);
}


ImageModel2::~ImageModel2() {

}


QHash<int, QByteArray> ImageModel2::roleNames() const{
    QHash<int, QByteArray> roles;
    roles[1] = "imageName";
    return roles;
}


int ImageModel2::rowCount(const QModelIndex &parent) const {
    Q_UNUSED(parent);
    return _dataList_.count();

}


QVariant ImageModel2::data(const QModelIndex &index, int role) const {
    int row = index.row();
    if(row < 0 || row >= _dataList_.count()) {
        return QVariant();
    }
    QString fileName = _dataList_[row].imageName();
    return fileName;
}


BaseResult::JsonResult ImageModel2::openDir(QString dir) {
    this->dir = dir.mid(8);
    QDir* dir_ptr = new QDir(this->dir);
    if (!dir_ptr->exists()) {
        delete dir_ptr;
        dir_ptr = nullptr;
        return BaseResult(BaseResult::FAILED, "文件目录不存在").toJson();
    }

    dir_ptr->setNameFilters(QStringList({"*.png", "*.jpg", "*.jpeg", "*.bmp"}));
    QStringList fileList = dir_ptr->entryList(QDir::Files);
    emit beginResetModel();
    _dataList_.clear();
    for(QString file: fileList) {
        qDebug() << file;
        ImageLabelModel imageLabelModel(file);
        _dataList_.append(imageLabelModel);
    }
    emit endResetModel();
    return BaseResult(BaseResult::SUCCEED, "打开成功").toJson();
}


int ImageModel2::count() const {
    return rowCount(QModelIndex());
}
